package com.example.seckill.service;

import com.example.seckill.properties.SeckillProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
public class SeckillLoadBalancer {

    @Autowired
    private SeckillProperties seckillProperties;

    private final AtomicInteger counter = new AtomicInteger(0);

    public String selectServer() {
        int count = counter.incrementAndGet();
        int serverIndex = getServerIndex(count);

        String selectedServer = seckillProperties.getServers().get(serverIndex);
        log.debug("Request {} routed to server: {}", count, selectedServer);

        return selectedServer;
    }

    private int getServerIndex(int count) {
        // 根据服务器权重计算
        // 假设server1权重3，server2权重2
        return (count % 5 <= 2) ? 0 : 1;
    }
}


